package com.mate.cloud.lottery;

import com.alibaba.fastjson2.JSON;
import com.mate.cloud.core.util.CollectionUtils;
import com.mate.cloud.core.util.ObjectUtil;
import com.mate.cloud.lottery.constants.LotteryConstants;
import com.mate.cloud.lottery.constants.RedisKeyManager;
import com.mate.cloud.lottery.domain.Lottery;
import com.mate.cloud.lottery.domain.vo.LotteryVO;
import com.mate.cloud.lottery.mapper.LotteryMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@Component
public class LoadDataApplicationRunner implements ApplicationRunner {


    @Resource
    RedisTemplate<String, Object> redisTemplate;


    @Resource
    LotteryMapper lotteryMapper;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("=========begin load lottery data to Redis===========");
        //加载当前抽奖活动信息
        Lottery lottery = lotteryMapper.selectById(1);
        if (ObjectUtil.isNotEmpty(lottery)) {
            String lotteryRedisKey = RedisKeyManager.getLotteryRedisKey(lottery.getId());
            redisTemplate.opsForValue().set(lotteryRedisKey, lottery);
            log.info("Loaded single lottery data to Redis, key={}, value={}", lotteryRedisKey, lottery);
        } else {
            log.warn("No lottery found for ID=1");
        }
        log.info("=========finish load lottery data to Redis===========");

//        loadLotteries();
    }

    private void loadLotteries() {
        List<Lottery> lotteries = lotteryMapper.selectList(null);
        if (CollectionUtils.isNotEmpty(lotteries)) {
            cacheLottery(LotteryConstants.LOTTERY, lotteries);
            log.info("Loaded {} lottery records to Redis", lotteries.size());
        } else {
            log.warn("No lottery data found in DB");
        }
    }


    /**
     * 数据缓存
     *
     * @param lotteryList
     */
    private void cacheLottery(String redisKey, List<Lottery> lotteryList) {

        if (CollectionUtils.isEmpty(lotteryList)) {
            return;
        }

        redisTemplate.delete(redisKey);
        log.info("############################################################");
        log.info("初始化rss新闻到redis中,size:{}", lotteryList.size());

        redisTemplate.executePipelined((RedisCallback<LotteryVO>) redisConnection -> {
            redisConnection.openPipeline();
            for (Lottery lottery : lotteryList) {
                byte[] keyBytes = RedisKeyManager.getLotteryRedisKey(lottery.getId()).getBytes(StandardCharsets.UTF_8);
                redisConnection.lPush(keyBytes, JSON.toJSONString(lottery).getBytes(StandardCharsets.UTF_8));
            }
            redisConnection.closePipeline();
            return null;
        });
        log.info("初始化完成,key:{}", redisKey);
        log.info("############################################################");

    }
}